// punch.js
var app = getApp();
var util = require('../../utils/util.js')
var glo = require('../../utils/global.js')
var bibleData = require('../../utils/bible.js')
var oldbook = "";
var newbook = "";
var lastTapDiffTime = 0;

var arr = [];
for (var i = 1; i <= 100; i++) {
  arr.push(i);
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 1,
    array: arr,
    userInfo: [],
    punchCount: 0,
    staticTop: '34%',
    punchTop:'26%',
    biblename: "菜谱",
    dk: decodeURI('%E6%89%93%E5%8D%A1'),
    pageEnable: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    oldbook = bibleData.oldbooks;
    newbook = bibleData.newbooks;
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        console.log(res);
        if (res.windowWidth > 500) {
          that.setData({
            staticTop: '40%',
            punchTop:'36%'
          })
        }
      }
    })
    var v = "%E5%9C%A3%E7%BB%8F"
    if (glo.validBible()) {
      that.setData({ biblename: decodeURI(v), pageEnable: true });
      wx.setNavigationBarTitle({
        title: decodeURI('%E6%89%93%E5%8D%A1')+ '目标',
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  nearReadTap: function(e) {
    // var currentTime = new Date().getTime();
    // var nowDate = new Date(glo.fbtime);
    var self = this;
  //  if ((currentTime - nowDate.getTime()) > 0) {
      var curTime = e.timeStamp;
      var lastTime = lastTapDiffTime;
      if (lastTime > 0) {
        if (curTime - lastTime < 300) {
          console.log("双击事件");
          lastTapDiffTime = curTime;
          return;
        }
      }
      lastTapDiffTime = curTime;

      var bookId = e.target.dataset.bookid;
      var chapterId = e.target.dataset.chapterid;
      var bookName = e.target.dataset.bookname;
      var chapterCount = e.target.dataset.chaptercount;
      var verseid = e.target.dataset.verseid;
      var content = "";
      var keyid = "CH" + "-" + bookId + "-" + chapterId;

      wx.getStorage({
        key: "bk" + bookId,
        success: function(res) {
          wx.showLoading({
            title: "正在加载...",
            mask: true
          });
          var bookData = res.data;
          for (var i = 0; i < bookData.length; i++) {
            if (chapterId == bookData[i].chapterId) {
              content = bookData[i].content;
              console.log("缓存读取" + bookName + "第" + chapterId + "章");
              wx.navigateTo({
                url: '../content/content' + '?bookName=' + bookName + '&chapterId=' + chapterId + '&chapterCount=' + chapterCount + '&bookId=' + bookId + '&content=' + content + '&lid=' + verseid + '&from=3',
                success: function(res) {
                  wx.hideLoading();
                  // success
                },
                fail: function() {
                  wx.hideLoading();
                  // fail
                }
              })
            }
          }
        },
        fail: function() {
          wx.showLoading({
            title: "首次加载该卷",
            mask: true
          });
          wx.request({
            url: glo.https + '/chapter/list_bookid?bookId=' + bookId,
            method: 'GET',
            success: function(res) {
              wx.setStorage({ //添加缓存
                key: "bk" + bookId,
                data: res.data
              });
              var bookData = res.data;
              for (var i = 0; i < bookData.length; i++) {
                if (chapterId == bookData[i].chapterId) {
                  content = bookData[i].content;
                  console.log("缓存读取" + bookName + "第" + chapterId + "章");
                  wx.navigateTo({
                    url: '../content/content' + '?bookName=' + bookName + '&chapterId=' + chapterId + '&chapterCount=' + chapterCount + '&bookId=' + bookId + '&content=' + content + '&lid=' + verseid + '&from=3',
                    success: function(res) {
                      wx.hideLoading();
                      // success
                    },
                    fail: function() {
                      wx.hideLoading();
                      wx.showToast({
                        title: '加载失败，请检查网络',
                        icon: 'loading',
                        duration: 1000
                      })
                      // fail
                    }
                  })
                }
              }
            }
          })
        }
      });
    // } else {
    //   wx.showToast({
    //     title: '正在加载......',
    //   })
    // }


  },

  bindPickerChange: function(e) {
    var that = this;
    var index = e.detail.value;
    var array = that.data.array;
    var target = array[index];
    var userInfo = this.data.userInfo;
    var todaycount = this.data.todaycount;
    var today = 'today';
    if (todaycount >= target) {
      today = 'today_ok';
    }
    wx.request({
      url: glo.https + '/person/target_update',
      data: {
        target: target,
        userid: that.data.userInfo.userId
      },
      success: function(res2) {
        if (res2.data == true) {
          userInfo.target = target;
          app.setUserInfo(userInfo);
        }
      }
    })

    this.setData({
      index: index,
      today: today
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo) {
      var punch = userInfo.punch;
      var result = glo.punchCalc1(punch);

      //更新数据
      var arr1 = userInfo.punch.replace(/#/g, "").split(';').slice(1);
      var target = userInfo.target;
      var today = 'today';
      var todaycount = result.todaycount;
      var timestamp = new Date().getTime();
      var nonce = glo.randomWord(false, 32);
      var signature = glo.encryptToken(timestamp, nonce);

      //获取最近
      wx.request({
        url: glo.https + '/person/gettarget',
        data: {
          signature: signature,
          timestamp: timestamp,
          nonce: nonce,
          userid: userInfo.userId
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res0) {
          console.log(res0);
          var result1 = res0.data;
          var weekcount = result1[0];
          var moncount = result1[1];
          var yearcount = result1[2];
          var starsWeek = glo.punchCalc2(weekcount, 7);
          var starsMon = glo.punchCalc2(moncount, 30);
          var starsYear = glo.punchCalc2(yearcount, 365);
          that.setData({
            moncount: moncount,
            yearcount: yearcount,
            weekcount: weekcount,
            starsWeek: starsWeek,
            starsMon: starsMon,
            starsYear: starsYear
          });
        },
        fail: function(res1) {

        }
      });

      //获取近一年读一本进度
      wx.request({
        url: glo.https + '/person/getbibletarget',
        data: {
          userid: userInfo.userId
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res0) {
          var pencent = parseInt(res0.data);
          that.setData({
            bibletarget: pencent,
            punchCount: arr1.length
          });
        },
        fail: function(res1) {

        }
      });





      var array = that.data.array;
      var index = 0;
      for (var i = 0; i < array.length; i++) {
        var value = array[i];
        if (value == target) {
          index = i;
        }
      }

      var lastread = userInfo.lastRead;
      if (lastread != "") {
        var arr00 = lastread.split("-");
        var bookId = parseInt(arr00[0]);
        var chapterId = parseInt(arr00[1]);
        var bookName = arr00[2];
        var chapterCount = parseInt(arr00[3]);
        var verseId = 1;
        if (chapterId < chapterCount) {
          chapterId = chapterId + 1;
        } else {
          chapterId = 1;
          if (bookId < 66) {
            bookId = bookId + 1;
          } else {
            bookId = 1;
          }
          if (bookId > 39) {
            bookName = newbook[bookId - 40].bookName;
            chapterCount = newbook[bookId - 40].chapterCount;
          } else {
            bookName = oldbook[bookId - 1].bookName
            chapterCount = newbook[bookId - 1].chapterCount;
          }
        }
        var verseId = arr00[4];
        lastread = bookName + "第" + chapterId + "章";
        // var currentTime = new Date().getTime();
        // var nowDate = new Date(glo.fbtime);

      //  if ((currentTime - nowDate.getTime()) > 0) {
          lastread = bookName + "第" + chapterId + "章";
        // } else {
        //   lastread = '';
        // }
        that.setData({
          bookId: bookId,
          chapterId: chapterId,
          bookName: bookName,
          chapterCount: chapterCount,
          verseId: verseId,
          lastread: lastread,
          opa: "opacity:1"
        });
      } else {
        that.setData({
          opa: "display:none"
        });
      }

      /*
      for (var i = 0; i < arr1.length; i++) {
        var c0 = arr1[i];
        if (c0 != "") {
          allcount = allcount + 1;
          c0 = c0.replace(/#/g, "");
          var arr2 = c0.split("-");
          var c1 = arr2[0]+"-"+arr2[1]+"-"+arr2[2];
          var c2 = arr2[0] + "-" + arr2[1];
          var c3=arr2[0];
          if (c1 == currDate) {
            todaycount = todaycount + 1;
          }
          if (c2== currMon) {
            moncount = moncount + 1;
          }
          if (c3 == currYear) {
            yearcount = yearcount + 1;
          }
        }
      }
      */
      // if(todaycount>=target){
      //   today='today_ok';
      // }
      that.setData({
        todaycount: todaycount,
        index: index,
        userInfo: userInfo,
        today: today
      });

    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function() {

  }
})